import AudioMgr from "../manager/AudioMgr";
import mi from "../MI";

const { ccclass } = cc._decorator;


/**
 * 根结点 Widget 设置
 *     选中 Horizontal Center, 输入 0
 *     选中 Vertical Center, 输入 0
 * 根结点 Node Size 属性要足够大(可以使用代码设置 this.node.setContentSize(mi.UIRoot.getContentSize());)
 * 不知道为什么要这样设置才能适配父节点
 * 
 * Left Top Right Bottom 都设置为 0 不起作用, 感觉是动画缩放的问题
 */
@ccclass
export default class AlertView extends cc.Component {
    private label: cc.Label = null;
    private btnOk: cc.Node = null;
    private btnCancel: cc.Node = null;

    private _cbOk: Function = null;
    private _cbCancel: Function = null;

    private _fadeOutFinish: cc.ActionInterval = null;


    protected onLoad(): void {
        this.label = cc.find('alert_background/label', this.node).getComponent(cc.Label);
        this.btnOk = cc.find('alert_background/alert_ok', this.node);
        this.btnCancel = cc.find('alert_background/alert_cancel', this.node);

        this.node.setContentSize(mi.UIRoot.getContentSize());

        // 初始化绽放和透明度
        this.node.setScale(2);
        this.node.opacity = 0;

        // 按钮不能点击
        this.btnOk.getComponent(cc.Button).interactable = false;
        this.btnCancel.getComponent(cc.Button).interactable = false;

        let actionFadeOut = cc.spawn(cc.fadeTo(0.3, 0), cc.scaleTo(0.3, 2));
        let finished = cc.callFunc(() => {
            this.node.removeFromParent(false);
        }, this);

        // 弹出动画
        this._fadeOutFinish = cc.sequence(actionFadeOut, finished);

        // 按钮点击事件
        this.btnOk.on('click', this.onButtonClicked, this);
        this.btnCancel.on('click', this.onButtonClicked, this);
    }


    public show(text: string, cbOk?: Function, cbCancel?: Function): void {
        let actionFadeIn = cc.spawn(cc.fadeTo(0.3, 255), cc.scaleTo(0.3, 1));
        let actionClickOk = cc.callFunc(() => {
            this.btnOk.getComponent(cc.Button).interactable = true;
            this.btnCancel.getComponent(cc.Button).interactable = true;
        });
        let actionSeq = cc.sequence(actionFadeIn, actionClickOk);

        this.node.runAction(actionSeq);

        if (text) this.label.string = text;

        if (cbCancel) {
            this._cbCancel = cbCancel;
        } else {
            this.btnCancel.active = false;
            const wg = this.btnOk.getComponent(cc.Widget);
            wg.isAlignHorizontalCenter = true;
            // 手动刷新 widget, 立即生效
            wg.updateAlignment();
        }

        this._cbOk = cbOk;
    }


    private onButtonClicked(event: cc.Button): void {
        switch (event.target.name) {
            case 'alert_ok':
                if (this._cbOk) this._cbOk();
                break;
            case 'alert_cancel':
                if (this._cbCancel) this._cbCancel();
                break;
        }

        AudioMgr.playSFX(mi.buttonSound);

        this.node.runAction(this._fadeOutFinish);
    }
}
